<template>
	<cl-page>
		<view
			class="page-wrap"
			:style="{ width: info.style.width, height: `calc(${info.style.height} + 180rpx)` }"
		>
			<view class="head">
				<view class="mr-20">
					<cl-button type="primary" round @tap="onRefresh">刷新</cl-button>
				</view>
				<view>{{ info.data?.pname }}</view>
			</view>

			<!-- 展位图 -->
			<view
				class="booth"
				:style="{ width: info.style.width, height: `calc(${info.style.height} + 120rpx)` }"
			>
				<view class="table-wrap">
					<view class="table-wrap_info">
						<view class="info-left">
							<view class="cell">
								<text class="cell-label">展会年份:</text>
								<text class="cell-value">{{ info.data?.ptime }}</text>
							</view>
							<view class="cell">
								<text class="cell-label">展区名称:</text>
								<text class="cell-value">{{ info.data?.ename }}</text>
							</view>
						</view>
						<view class="info-right">
							<!-- <cl-tag :type="info.status == 1 ? 'primary' : 'info'">{{
								info.status == 0 ? "未开始" : info.status == 1 ? "进行中" : "已结束"
							}}</cl-tag> -->
						</view>
					</view>

					<!-- <view class="table-wrap_title" v-show="info.list.length > 0">
						<text class="mr-40">展会排列图</text>
						<text style="font-size: 12px">
							<i class="iconfont icon-jingzhuangwujin" />
							<text style="color: #c0c0c0; margin-left: 10rpx">表示精装</text>
						</text>
					</view> -->

					<view
						class="table-wrap_content"
						border
						:style="{ width: info.style.width, height: info.style.height }"
					>
						<view
							class="booth-wrap"
							:style="{ width: info.style.width, height: info.style.height }"
						>
							<!-- :style="{ width: info.style.width, height: info.style.height }" -->
							<view class="wall"></view>
							<view
								v-for="(item, cIndex) in info.list"
								:key="cIndex"
								class="booth-cell"
								:class="[
									isDisabled(item) ? 'disabled' : '',
									isSelected(item) ? 'selected' : '',
									sel.includes(item.EBNo) ? 'checked' : '',
									item.type == 0 ? 'booth' : '',
									item.type == 2 ? 'aisle' : '',
									item.type == 3 ? 'exit' : '',
									item.type == 4 ? 'wall' : '',
									item.type == 7 ? 'toilet' : '',
								]"
								:style="{
									top: item.top + 'px',
									left: item.left + 'px',
									width: item.width + 'px',
									height: item.height + 'px',
									background: item.color,
								}"
								@tap="onSelect(item)"
							>
								<!-- 装修等级 -->
								<view v-if="item.type == 0 && item.level" class="level">
									<i class="iconfont icon-jingzhuangwujin" />
								</view>
								<view class="col-line">
									<text class="col-line_text" />
									<text>{{ item.EBNo }}</text>
								</view>
								<!-- 展位出入口 -->
								<view v-if="item.type == 0 && item.entrance" class="col-line">
									<text class="col-line_text"> 出入口：{{ item.entrance }}</text>
								</view>
							</view>
						</view>
					</view>

					<global-empty v-if="info.list.length == 0" text="暂无展位图" />
				</view>
			</view>
			<!-- 操作按钮 -->
			<view class="foot" v-if="sel.length > 0">
				<cl-button class="foot-btn" v-if="sel.length == 1" type="success" round @tap="onContract"
					>查看合同</cl-button
				>
				<cl-button class="foot-btn" type="primary" round @tap="onConfirm">占位</cl-button>
				<cl-button class="foot-btn" v-if="sel.length == 1" type="warning" round @tap="onCancel"
					>取消占位</cl-button
				>
			</view>
		</view>
	</cl-page>

	<!-- 占位 -->
	<cl-confirm :ref="setRefs('confirmRef')">
		<view class="modify-wrap">
			<view class="modify-wrap_list">
				<cl-select
					v-model="confirmForm.dealerId"
					:options="options.employee"
					placeholder="选择客户"
				></cl-select>
				<!-- <cl-textarea
					v-model="confirmForm.remark"
					placeholder="备注"
					:height="112"
				></cl-textarea> -->
			</view>
		</view>
	</cl-confirm>
	<!-- 取消 -->
	<cl-confirm :ref="setRefs('confirmCancelRef')" />
</template>

<script lang="ts" setup>
import { onLoad } from "@dcloudio/uni-app";
import { ref, defineComponent, reactive, computed } from "vue";

import { useCool, useStore } from "/@/cool";
import { BOOTH_TYPE, BOOTH_LEVEL } from "./dict";
import { maxBy } from "lodash";

const { app, user, dict } = useStore();
const { router, service, ui, refs, setRefs } = useCool();

const userInfo = computed(() => {
	return user.info;
});

console.info("userInfo", userInfo);

const confirmForm = reactive<any>({
	dealerId: null, // 客户编号
	remark: "",
	turns: [
		{
			exhibitionId: null, // 展会编号
			EBNo: null, // 展位编号
		},
	],
});

const options = reactive<any>({
	type: BOOTH_TYPE,
	level: BOOTH_LEVEL,
	employee: computed(() => dict.get("employee")),
});

// const employee = computed(() => {
// 	return dict.get("employee");
// })

const info = reactive<any>({
	data: {
		pid: null,
		eid: null,
		ptime: null,
		pname: null,
		ename: null,
		type: "view", // view 查看, edit 编辑
	},
	style: {
		width: "100%",
		height: "100%",
	},
	list: [],
	get: () => {
		// ui.showLoading();
		uni.showLoading({
			title: "加载中...",
		});

		service.booth
			.exhibitionLocationList({
				exhibitionId: info.data?.eid,
				projectId: info.data?.pid,
				projectTime: info.data?.ptime,
			})
			.then((res: any) => {
				if (res.success) {
					info.list =
						res.data?.list.map((e: any) => {
							return {
								...e,
								top: Number(e.top),
								left: Number(e.left),
							};
						}) ?? [];

					// 用lodash计算列表中left最大值
					const maxLeft = maxBy(info.list, "left");
					info.style.width = maxLeft?.left
						? `${maxLeft?.left + Number(maxLeft?.width || 50) + 50}px`
						: "100%";

					// 用lodash计算列表中top最大值
					const maxTop = maxBy(info.list, "top");
					info.style.height = maxTop?.top
						? `${maxTop?.top + Number(maxTop?.height || 50) + 50}px`
						: "100%";

					console.info("info.style", info.style);
				}
			})
			.finally(() => {
				// ui.hideLoading();
				uni.hideLoading();
			});
	},
});

// function groupByX(exhBooths: any[]) {
// 	const grouped: any = [];

// 	// 遍历展位数组，根据 x 轴进行分组
// 	exhBooths.forEach((booth) => {
// 		const x = booth.x;
// 		if (!grouped[x]) {
// 			grouped[x] = [];
// 		}
// 		grouped[x].push(booth);
// 	});

// 	// 将对象的值转换为二维数组
// 	return Object.values(grouped);
// }

function init() {
	info.get();
}

// 刷新
function onRefresh() {
	info.get();
}

// 是否不可用
function isBan(item: any) {
	return (
		item.enabled == 0 || item.type == 2 || item.type == 3 || item.type == 4 || item.type == 5
	);
}

// 是否禁用
function isDisabled(item: any) {
	return info.data.type == "edit" && item.empId && item.empId != userInfo.value?.empId;
}

// 是否已经占位
function isSelected(item: any) {
	return item.empId && item.empId == userInfo.value?.empId;
}

// 操作项 **** start ****
function getDict(val: any, list: any[]) {
	if (!val) {
		return "-";
	}
	const _item = list.find((item) => item.value == val);
	return _item ? _item.label : "-";
}

// 选择
const sel = ref<any[]>([]);
function onSelect(row: any) {
	if (info.data.type == "view") return false;

	if (row.empId && row.empId != userInfo.value?.empId) {
		ui.showToast("该展位已被占用，请重新选择");
	}

	if (sel.value.includes(row.EBNo)) {
		sel.value.splice(sel.value.indexOf(row.EBNo), 1);
	} else {
		sel.value.push(row.EBNo);
	}
}

// 确认
function onConfirm() {
	// if (row.enabled == 0 || row.checked == 1) {
	// 	ui.showToast("该展位已被占用，请重新选择！");
	// 	return false;
	// }

	if (info.data.type == "view") return false;

	if (sel.value.length == 0) {
		ui.showToast("请先选择展位！");
		return false;
	}

	refs.value.confirmRef.open({
		title: `是否占用选中的展位！`,
		message: ``,
		cancelButtonText: "取消",
		confirmButtonText: "确认",
		callback(action: any) {
			if (action == "confirm") {
				const params: any = {
					projectId: info.data?.pid,
					projectTime: info.data?.ptime,
					turns: sel.value.map((item: any) => {
						return {
							exhibitionId: info.data?.eid,
							EBNo: item,
						};
					}),
				};

				if (confirmForm?.remark) {
					params.remark = confirmForm?.remark;
				}

				// user.logout();
				service.booth.saveContract(params).then((res: any) => {
					ui.showToast("展位占位成功！");
					sel.value = [];
					info.get();
				});
			}
		},
	});
}

// 取消
function onCancel() {
	if (info.data.type == "view") return false;

	if (sel.value.length == 0) {
		ui.showToast("请先选择展位！");
		return false;
	}

	if (sel.value.length != 1) {
		ui.showToast("取消占位只能选择一个展位！");
		return false;
	}

	const _booth = info.list.find((item: any) => item.EBNo == sel.value[0]);

	console.info("_booth", _booth, _booth.empId, userInfo.value?.empId);

	if (_booth.empId && _booth.empId != userInfo.value?.empId) {
		ui.showToast("该展位已被占用，请重新选择");
	}

	refs.value.confirmCancelRef.open({
		title: `是否取消选中的展位！`,
		message: ``,
		cancelButtonText: "取消",
		confirmButtonText: "确认",
		callback(action: any) {
			if (action == "confirm") {
				const params: any = {
					billid: _booth.saleBillId,
				};

				service.booth.deleteContract(params).then((res: any) => {
					ui.showToast("展位取消占位成功！");
					sel.value = [];
					info.get();
				});
			}
		},
	});
}

// 查看合同
function onContract() {
	const _booth = info.list.find((item: any) => item.EBNo == sel.value[0]);

	console.info("_booth", _booth);

	if (!_booth.saleBillId) {
		ui.showToast("该展位未占位，请先占位！");
		return false;
	}

	if (_booth.empId && _booth.empId != userInfo.value?.empId) {
		ui.showToast("不是该展位的占位者，无法查看！");
	}

	uni.navigateTo({
		url: `/pages/index/contract?billid=${_booth.saleBillId}`,
	});

	sel.value = [];
}

onLoad((options: any) => {
	if (options) {
		info.data = options;
	}

	dict.refresh();

	init();
});
</script>

<style lang="scss" scoped>
.page-wrap {
	padding: 1rpx;
	.head {
		display: flex;
		align-items: center;
		// justify-content: space-between;
		margin: 10rpx 0;
		padding: 10rpx 20rpx;
	}
	.booth {
		padding: 10rpx;
		background-color: #fff;
	}
	.foot {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		margin: 20rpx 0;
		padding: 0 20rpx 20rpx;
		.foot-btn {
			width: 240rpx;
			height: 100rpx !important;
			line-height: 100rpx !important;
			font-size: 36rpx !important;
		}
	}
	.table-wrap {
		width: 100%;
		height: 100%;
		// 表单配置
		&_info {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 20rpx;
			.info-left {
				display: flex;
				align-items: center;
			}

			.cell {
				margin-right: 20rpx;
				&-label {
					color: #999;
					margin-right: 10rpx;
				}
			}
		}

		// 标题
		&_title {
			margin-bottom: 30rpx;
		}

		// table内容
		&_content {
			width: 100%;
			// border: 1px solid #ccc;
			// width: 100%;
			height: calc(100vh - 300rpx);
			// overflow-x: scroll;
			// overflow-x: hidden;
			// overflow-y: scroll;
			// position: relative;
			background-color: #f7f7f7;
			// display: flex;
			.booth-wrap {
				position: relative;
			}
			// 墙体
			.wall {
				width: calc(100% - 20rpx);
				height: calc(100% - 20rpx);
				position: absolute;
				z-index: 2;
				border: 20rpx solid #a3a3a3;
			}
			// 展位
			.booth-cell {
				position: absolute;
				z-index: 4;
				border-radius: 2px;
				border: 1px solid #ccc;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				&.checked {
					border-color: #007aff !important;
				}
				&:hover {
					background: #f0f0f0;
				}
				&.selected {
					// background: #f0f0f0 !important;
					&:before {
						content: "";
						position: absolute;
						top: 0;
						right: 0;
						// border-left: 5px solid transparent;
						// border-right: 5px solid transparent;
						// border-bottom: 10px solid #007bff;
						width: 0;
						height: 0;
						border-left: 8px solid transparent; /* 右边直角的颜色 */
						border-right: 8px solid #007bff;
						border-bottom: 8px solid transparent; /* 右边直角的颜色 */
						// transform: rotate3d(0, 0, 1, 50deg);
					}
				}
				&.disabled {
					background: #f0f0f0 !important;
				}
				.level {
					position: absolute;
					top: 0;
					right: 0;
					&::after {
						content: "";
						position: absolute;
						top: -57px;
						right: -57px;
						width: 0;
						height: 0;
						border: 32px solid transparent;
						border-right: 60px solid #ffd700;
						transform: rotate(135deg);
					}
					.iconfont {
						position: relative;
						z-index: 2;
					}
				}
				.col-line {
					display: flex;
					align-items: center;
					margin-bottom: 8px;
					height: 18px;
					color: #000;
					&_text {
						margin-right: 4px;
						color: #000;
						font-size: 12px;
						flex-shrink: 0;
					}
				}
			}
		}
	}
	.modify-wrap {
		// padding: 0 0 10rpx 0;
		&_list {
			// height: 112rpx;
			text-align: left;
			border-bottom: 0.7px solid $uni-border-color;
		}
	}
}
</style>
